<template>
  <div>
    <zhlDialog
      title="接口选择"
      ref="selectApilist"
      width="1260px"
      height="790px"
      class="my-dialog"
    >
      <a-tabs default-active-key="1">
        <a-tab-pane key="1" tab="接口管理" force-render>
          <el-row>
            <el-col :span="8" class="inputform">
              <div>表单名称:</div>
              <el-input
                placeholder="表单名称"
                v-model="queryparam.pagename"
              ></el-input>
            </el-col>
            <el-col :span="8" class="inputform">
              <div>表单编码:</div>
              <el-input
                placeholder="表单编码"
                v-model="queryparam.description"
              ></el-input>
            </el-col>
            <el-col :span="8" class="inputform">
              <div>方法名:</div>
              <el-input
                placeholder="方法名"
                v-model="queryparam.methodcode"
              ></el-input>
            </el-col>
            <el-col :span="8" class="inputform">
              <div>方法名称:</div>
              <el-input
                placeholder="方法名称"
                v-model="queryparam.methodname"
              ></el-input>
            </el-col>
            <el-col :span="16" class="inputform">
              <el-button type="primary" @click="$refs.gridlist.loadData(1)"
                >查询</el-button
              >
            </el-col>
          </el-row>
          <gridlist
            :queryparam="queryparam"
            apicode="tappUser.queryApiList"
            ref="gridlist"
            :scopedSlots="scopedSlots"
          >
            <div slot="method_type" slot-scope="record">
              {{
                record.row.method_type !== null
                  ? methodtype[record.row.method_type]
                  : ''
              }}
            </div>
            <template slot="operation" slot-scope="record">
              <a
                class="margin-a"
                href="javascript:;"
                style="margin-right: 5px;"
                @click="selectApi(record.row)"
                >选择</a
              >
            </template>
          </gridlist>
        </a-tab-pane>
        <a-tab-pane key="2" tab="Swagger接口">
          <el-row>
            <el-col :span="6" class="inputform">
              <div>doc地址:</div>
              <a-select
                style="width: 120px"
                v-model="swaggerHttp"
                @change="swaggerHttpChange"
              >
                <a-select-option
                  :value="item.value"
                  v-for="item in swaggerHttpList"
                  :key="item.value"
                >
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </el-col>
            <el-col :span="6" class="inputform">
              <div>分类名称:</div>
              <a-select style="width: 120px" v-model="tabType">
                <a-select-option
                  :value="item"
                  v-for="item in tabTypeList"
                  :key="item"
                >
                  {{ item }}
                </a-select-option>
              </a-select>
            </el-col>
            <el-col :span="6" class="inputform">
              <div>接口名称:</div>
              <el-input placeholder="接口名称" v-model="methodname"></el-input>
            </el-col>
            <el-col :span="6" class="inputform">
              <div>接口地址:</div>
              <el-input
                placeholder="接口地址"
                v-model="methodAddress"
              ></el-input>
            </el-col>
            <el-col :span="24" class="inputform">
              <el-button type="primary" @click="querySwagger()">查询</el-button>
            </el-col>
          </el-row>
          <a-table
            :data-source="swaggerList"
            border
            style="width: 100%"
            :scroll="{ y: 350 }"
            :columns="swaggercolumns"
            :pagination="false"
          >
            <div slot="operation" slot-scope="text, scope">
              <a
                class="margin-a"
                href="javascript:;"
                style="margin-right: 5px;"
                @click="selectswaggerApi(scope)"
                >选择</a
              >
            </div>
          </a-table>
        </a-tab-pane>
      </a-tabs>
    </zhlDialog>
    <zhlDialog
      title="调用接口赋值"
      ref="apisettings"
      width="1260px"
      class="my-dialog"
      height="790px"
    >
      <paramedit
        ref="paramedit"
        :param="param"
        :paramurl="paramurl"
      ></paramedit>
      <a-row class="filterbottom">
        <div class="operation">
          <a-button type="primary" @click="nextClick()">确定</a-button>
        </div>
      </a-row>
    </zhlDialog>
  </div>
</template>
<script>
import { getApiConfigById } from '@/api/packageInterface.js'
import { getlist } from '@/components/formdesign/swaggerComm.js'
import paramedit from '@/components/formdesign/paramedit.vue'
export default {
  props: [
    'apicode',
    'methodType',
    'sourceApiId',
    'controlInfo',
    'controlId',
    'controlType',
    'isparamset',
    'apiname'
  ],
  data() {
    return {
      sourceApi: this.apicode,
      sourceName: this.apiname,
      swaggerHttp: '',
      tabType: '',
      methodname: '',
      methodAddress: '',
      swaggerList: [],
      swaggercolumns: [
        {
          title: '请求路径',
          align: 'center',
          dataIndex: 'path',
          width: '320'
        },
        {
          title: '接口说明',
          align: 'center',
          dataIndex: 'summary',
          width: '320'
        },
        {
          title: '请求类型',
          align: 'center',
          dataIndex: 'methodType',
          width: '120'
        },
        {
          title: '接口类别',
          align: 'center',
          dataIndex: 'tabType',
          width: '120'
        },
        {
          title: '操作',
          align: 'center',
          dataIndex: 'operation',
          width: '120',
          scopedSlots: {
            customRender: 'operation'
          }
        }
      ],
      swaggerHttpList: [],
      tabTypeList: [],
      queryparam: {
        pagename: undefined,
        description: undefined,
        methodcode: undefined,
        methodname: undefined,
        methodtype: this.methodType
      },
      methodtype: ['', '列表Api', '查询Api', '操作Api', '对象Api'],
      scopedSlots: ['method_type'],
      swaggerJsonInfo: {},
      swaggerAllList: [],
      param: {},
      paramurl: {},
      paramlist: {},
      resultjson: null,
      ajaxType: 'apicode',
      fromid: ''
    }
  },
  components: { paramedit },
  methods: {
    selectApi(rows) {
      this.ajaxType = 'apicode'
      this.param = {}
      this.paramurl = {}
      this.resultjson = null
      this.sourceApi = rows.call_method_code
      this.sourceName = rows.method_name
      this.fromid = rows.fromid
      if (this.isparamset === false) {
        this.assignment()
        if (this.$refs.selectApilist !== undefined) {
          this.$refs.selectApilist.visible = false
        }
      } else {
        getApiConfigById(rows.fid).then(res => {
          const paramconfig = JSON.parse(res.data.paramConfig)
          for (let i = 0; i < paramconfig.length; i++) {
            if (paramconfig[i].property === 'body') {
              this.param = this.getparamconfig(paramconfig[i].children)
            } else if (paramconfig[i].property === '$query') {
              this.paramurl = this.getparamconfig(paramconfig[i].children)
            }
          }
          this.$refs.apisettings.visible = true
        })
      }
    },
    getparamconfig(list) {
      if (list !== undefined) {
        list.forEach(ee => {
          ee.paramvalue = ''
          this.getparamconfig(ee.children)
        })
      }
      return list
    },
    selectswaggerApi(rows) {
      this.ajaxType = 'swagger'
      const path = rows.path
      const methodType = rows.methodType
      const parameters = this.swaggerJsonInfo.paths[path][methodType].parameters
      this.param = {}
      this.paramurl = {}
      this.resultjson = null
      this.sourceApi = rows.ajaxpath
      this.sourceName = rows.summary
      parameters.forEach(ee => {
        if (ee.in === 'body') {
          this.param = this.getbodyparamvalue(ee.schema.$ref)
        } else if (ee.in === 'query') {
          this.paramurl[ee.name] = ''
        }
      })
      this.resultjson = getlist(this.swaggerJsonInfo, path, methodType)
      // if (this.resultjson === undefined || this.resultjson === null) {
      //   this.$message.error('你选择的不是列表查询接口!')
      //   return
      // }
      if (this.isparamset === false) {
        this.assignment()
      } else {
        this.$refs.apisettings.visible = true
      }
    },
    getbodyparamvalue(jsonpath) {
      if (jsonpath === undefined) {
        return []
      }
      const jsonpatharry = jsonpath.split('/')
      let paramvalue = {}
      jsonpatharry.forEach(ee => {
        if (ee === '#') {
          paramvalue = this.swaggerJsonInfo
        } else {
          paramvalue = paramvalue[ee]
        }
      })
      const paramobj = []
      for (const propertname in paramvalue.properties) {
        if (
          paramvalue.properties[propertname].type === 'object' ||
          paramvalue.properties[propertname].type === undefined
        ) {
          const item = {
            property: propertname,
            required: false,
            paramtype: '',
            paramname: '',
            paramvalue: '',
            variabletype: 'Object',
            children: [],
            isfirst: false
          }
          item.children = this.getbodyparamvalue(
            paramvalue.properties[propertname].$ref
          )
          paramobj.push(item)
        } else if (paramvalue.properties[propertname].type === 'array') {
          const item = {
            property: propertname,
            required: false,
            paramtype: '',
            paramname: '',
            paramvalue: '',
            variabletype: 'Array',
            children: [],
            isfirst: false
          }
          item.children = this.getbodyparamvalue(
            paramvalue.properties[propertname].$ref
          )
          paramobj.push(item)
        } else {
          paramobj.push({
            property: propertname,
            required: false,
            paramtype: this.getvariabletype(
              paramvalue.properties[propertname].type,
              paramvalue.properties[propertname].format
            ),
            paramvalue: '',
            paramname: paramvalue.properties[propertname].description,
            variabletype: paramvalue.properties[propertname].type,
            children: [],
            isfirst: false
          })
        }
      }
      return paramobj
    },
    getvariabletype(type, format) {
      let variabletype = ''
      switch (type) {
        case 'integer':
          variabletype = 'V_INTEGER'
          break
        case 'boolean':
          variabletype = ''
          break
        case 'string':
          switch (format) {
            case 'date-time':
              variabletype = 'V_DATE'
              break
            case 'date':
              variabletype = 'V_DATE'
              break
            default:
              variabletype = ''
              break
          }
          break
        default:
          variabletype = ''
          break
      }
      return variabletype
    },
    openform() {
      this.$refs.selectApilist.visible = true
    },
    swaggerHttpChange(value) {
      if (value === undefined || value === '' || value === null) return
      this.tabTypeList = []
      this.swaggerList = []
      this.swaggerAllList = []
      this.tabType = ''
      this.methodname = ''
      this.methodAddress = ''
      this.tabTypeList.push('')
      this.$ajaxswagger(value, {}, 'get').then(res => {
        this.swaggerJsonInfo = res
        this.swaggerJsonInfo.tags.forEach(ee => {
          this.tabTypeList.push(ee.name)
        })
        for (const key in this.swaggerJsonInfo.paths) {
          const item = this.swaggerJsonInfo.paths[key]
          if (item.get === undefined || item.get === null) {
            this.swaggerList.push({
              ajaxpath:
                this.swaggerJsonInfo.basePath + key.substring(1, key.length),
              path: key,
              methodType: 'post',
              summary: item.post.summary,
              tabType: item.post.tags[0]
            })
          } else {
            this.swaggerList.push({
              ajaxpath:
                this.swaggerJsonInfo.basePath + key.substring(1, key.length),
              path: key,
              methodType: 'get',
              summary: item.get.summary,
              tabType: item.get.tags[0]
            })
          }
        }
        this.swaggerAllList = JSON.parse(JSON.stringify(this.swaggerList))
      })
    },
    querySwagger() {
      this.swaggerList = []
      this.swaggerAllList.forEach(ee => {
        let isbool = true
        if (
          isbool &&
          this.tabType !== '' &&
          ee.tabType.indexOf(this.tabType) < 0
        ) {
          isbool = false
        }
        if (
          isbool &&
          this.methodname !== '' &&
          ee.summary.indexOf(this.methodname) < 0
        ) {
          isbool = false
        }
        if (
          isbool &&
          this.methodAddress !== '' &&
          ee.path.indexOf(this.methodAddress) < 0
        ) {
          isbool = false
        }
        if (isbool) {
          this.swaggerList.push(ee)
        }
      })
    },
    assignment() {
      // if (this.controlInfo !== undefined) {
      //   if (
      //     this.controlInfo.options.source === undefined ||
      //     this.controlInfo.options.source === null
      //   ) {
      //     this.controlInfo.options.source = {}
      //   }
      //   this.controlInfo.options.source.type = this.ajaxType
      //   this.controlInfo.options.source.sourceApi = this.sourceApi
      //   this.controlInfo.options.source.result = this.resultjson
      //   this.controlInfo.options.source.paramlist = this.paramlist
      //   this.$emit('select', this.sourceApi)
      //   this.$emit('update:apicode', this.sourceApi)
      // } else {
      const source = {
        type: this.ajaxType,
        sourceApi: this.sourceApi,
        result: this.resultjson,
        paramlist: this.paramlist,
        sourceName: this.sourceName,
        fromid: this.fromid
      }
      this.$emit('select', source)
      this.$emit('update:apicode', this.sourceApi)
      // }
    },
    nextClick() {
      this.paramlist = JSON.parse(this.$refs.paramedit.getJSONStr())
      this.$refs.selectApilist.visible = false
      this.assignment()
      this.$refs.apisettings.visible = false
    },
    loadswaggerHttpList() {
      this.$ajaxswagger('/swagger-resources', {}, 'get').then(res => {
        res.forEach(ee => {
          const { name, url } = ee
          this.swaggerHttpList.push({ value: url, text: name })
        })
      })
    }
  },
  mounted() {
    this.loadswaggerHttpList()
  },
  watch: {
    apicode(newcode) {
      this.sourceApi = newcode
    }
  }
}
</script>
<style scoped>
.inputform div:first-child {
  width: 80px;
  display: inline-block;
  height: 40px;
  margin-top: 10px;
  margin-left: 10px;
}
.inputform .el-input {
  width: calc(100% - 100px);
  float: right;
}
.inputform .el-select {
  width: calc(100% - 100px);
  float: right;
}
.inputform button {
  margin-left: 5px;
  margin-right: 5x;
}
.filterbottom {
  margin-top: 8px;
  margin-left: 15px;
  margin-right: 10px;
}
.filterbottom button {
  float: right;
  margin-right: 10px;
  margin-bottom: 20px;
}
.operation {
  width: 200px;
  float: right;
}
</style>
